package vell.velllock.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import vell.velllock.object.WordDBInfo;
import vell.velllock.util.FileUtil;
import android.content.Context;
import android.util.Log;

public class WordDBUtil {
	private static String tarDBPath = "/data/data/vell.velllock/databases/";
	
	/**
	 * find database file and copy to 'data/data/databases/' directory
	 * @param context
	 * @throws IOException
	 */
	public static void refreshWordDB(Context context) throws IOException{
		//refresh sdcard database;
		File DBDir = new File(android.os.Environment.getExternalStorageDirectory().toString() + "/velllock");
		if(!DBDir.exists()) DBDir.mkdir(); // create velllock directory
		List<File> DBFiles = findDBFile(DBDir);
		initSdcardDB(DBFiles, context);
		
		//refresh assets database
		initAssetsDB("kaoyan.db", context);
	}
	
	/**
	 * copy database file to target directory
	 * @param DBFiles
	 * @param context
	 * @throws IOException
	 */
	private static void initSdcardDB(List<File> DBFiles, Context context) throws IOException{
		
		Iterator<File> it = DBFiles.iterator();
		while(it.hasNext()){
			File DBFile = (File) it.next();
			
			//copy to 'data/data/databases/' directory 
			// Path to the just created empty db
	    	File outFile = new File(tarDBPath + DBFile.getName());
	 
	    	// database is already exist;
	    	if(outFile.exists()) continue;
	    	else FileUtil.createFile(outFile);
			
			//Open your local db as the input stream
	    	InputStream myInput = new FileInputStream(DBFile);
	    	//Open the empty db as the output stream
	    	OutputStream myOutput = new FileOutputStream(outFile);
	    	FileUtil.copyFile(myInput, myOutput);
	    	
	    	//add a database info record to WordDBInfo
	    	if(addDBInfo(outFile, context) == false){
				outFile.delete();
			}
		}
	}
	
	/**
	 * initialize database in assets
	 * @param DBName
	 * @param context
	 * @throws IOException
	 */
	private static void initAssetsDB(String DBName, Context context) throws IOException{
		InputStream myInput = context.getAssets().open(DBName);
		// Path to the just created empty db
    	File outFile = new File(tarDBPath + DBName);
 
    	// database is already exist;
    	if(outFile.exists()) return;
    	else FileUtil.createFile(outFile);
    	
		OutputStream myOutput = new FileOutputStream(outFile);
    	FileUtil.copyFile(myInput, myOutput);
    	
    	//add a database info record to WordDBInfo
		WordDBInfoOperator WDIO = new WordDBInfoOperator(context);
		WordDBOperator WDO = new WordDBOperator(context, outFile);
    	WordDBInfo WDI = null;
		try {
			WDI = WDO.getWordDBInfo();
		} catch (Exception e) {
			e.printStackTrace();
			outFile.delete();
			return;
		}
		WDI.setActive(1);
		WDI.setDBFile(outFile.getAbsolutePath());
    	WDIO.insertDBInfo(WDI);
	}
	
	private static boolean addDBInfo(File DBFile, Context context){
		WordDBInfoOperator WDIO = new WordDBInfoOperator(context);
		WordDBOperator WDO = new WordDBOperator(context, DBFile);
    	WordDBInfo WDI = null;
		try {
			WDI = WDO.getWordDBInfo();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		WDI.setDBFile(DBFile.getAbsolutePath());
    	return WDIO.insertDBInfo(WDI);
	}
	
	private static List<File> findDBFile(File dir){
		if(!dir.isDirectory()) return null;
		File[] allFile = dir.listFiles();
		List<File> DBFiles = new ArrayList<File>();
		for(File file : allFile){
			if(file.isFile()){
				String fileName = file.getName();
				String nameExtension = fileName.substring(fileName.lastIndexOf(".") < 0 ? 0 : fileName.lastIndexOf(".")+1);
				Log.i("nameExtension", nameExtension);
				if(nameExtension.toLowerCase().equals("db")){
					DBFiles.add(file);
				}
			}
		}
		return DBFiles;
	}
}
